package guice.boot.archive.container.test;

import guice.boot.archive.container.model.BizModel;
import guice.boot.archive.container.service.ContainerHolder;
import guice.boot.archive.container.service.classloader.BizClassLoader;
import guice.boot.archive.exception.ArkRuntimeException;
import guice.boot.archive.spi.model.Biz;
import guice.boot.archive.spi.model.BizState;
import guice.boot.archive.spi.service.biz.BizManagerService;

import java.net.URL;


public class NoneDelegateTestClassLoader extends BizClassLoader {
    public NoneDelegateTestClassLoader(String bizIdentity, URL[] urls) {
        super(bizIdentity, urls);
        // since version 1.1.0, we support load extension from ark biz, we should register biz now.
        BizManagerService bizManagerService = ContainerHolder.getContainer().getService(
                BizManagerService.class);
        Biz testBiz = createTestBiz(bizIdentity);
        bizManagerService.registerBiz(testBiz);
        ((BizModel) testBiz).setBizState(BizState.ACTIVATED);
    }

    private Biz createTestBiz(String bizIdentity) {
        String[] bizNameAndVersion = bizIdentity.split(":");
        if (bizNameAndVersion.length != 2) {
            throw new ArkRuntimeException("error bizIdentity format.");
        }
        BizManagerService bizManagerService = ContainerHolder.getContainer().getService(
                BizManagerService.class);
        Biz testBiz = new BizModel().setBizName(bizNameAndVersion[0])
                .setBizVersion(bizNameAndVersion[1]).setClassLoader(this).setDenyImportPackages("")
                .setDenyImportClasses("").setDenyImportResources("").setBizState(BizState.RESOLVED);
        bizManagerService.registerBiz(testBiz);
        return testBiz;
    }
}
